package com.googlecode.gwtbb.client.shared.validation;

import com.googlecode.gwtbb.client.shared.GwtbbSmess;
import com.googlecode.gwtbb.client.shared.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Apr 30, 2008
 */
public class GwtbbValidator {
	public static String nonNegative(final Map<FieldId, Failure> failures, final FieldId fieldId, String numStr) {
		if (StringUtils.isEmpty(numStr))
			failures.put(fieldId, new Failure(GwtbbSmess.instance().required()));
		else {
			numStr = numStr.trim();
			try {
				if (Integer.parseInt(numStr) < 0)
					failures.put(fieldId, new Failure(GwtbbSmess.instance().noNegatives()));
			} catch (NumberFormatException e) {
				failures.put(fieldId, new Failure(GwtbbSmess.instance().invalidNumber()));
			}
		}
		return numStr;
	}

	public static String basicMinMax(final Map<FieldId, Failure> failures, final FieldId fieldId, String value, final int min, final int max) {
		value = StringUtils.aggressiveTrim(value);
		if (StringUtils.isEmpty(value))
			failures.put(fieldId, new Failure(GwtbbSmess.instance().required()));
		else {
			if (containsNonBasicCharacters(value)) {
				failures.put(fieldId, new Failure(GwtbbSmess.instance().nonBasicCharacters()));
			}
			if (value.length() < min) {
				failures.put(fieldId, new Failure(GwtbbSmess.instance().minimumLength(min)));
			} else if (value.length() > max)
				failures.put(fieldId, new Failure(GwtbbSmess.instance().maximumLength(max)));
		}
		return value;
	}

	public static String minMax(final Map<FieldId, Failure> failures, final FieldId fieldId, String value, final int min, final int max) {
		if (StringUtils.isEmpty(value))
			failures.put(fieldId, new Failure(GwtbbSmess.instance().required()));
		else {
			if (value.length() < min) {
				failures.put(fieldId, new Failure(GwtbbSmess.instance().minimumLength(min)));
			} else if (value.length() > max)
				failures.put(fieldId, new Failure(GwtbbSmess.instance().maximumLength(max)));
		}
		return value;
	}

	public static String max(final Map<FieldId, Failure> failures, final FieldId fieldId, String value, final int max) {
		value = StringUtils.aggressiveTrim(value);
		if (value != null && value.length() > max)
			failures.put(fieldId, new Failure(GwtbbSmess.instance().maximumLength(max)));
		return value;
	}

	public static Map<FieldId, Failure> newMap() {
		return new HashMap<FieldId, Failure>(4, 1);
	}

	public GwtbbValidator() {
		throw new UnsupportedOperationException("don't instantiate me i'm for static methods");
	}

	private static boolean containsNonBasicCharacters(String value) {
		for (int i = 0; i < value.length(); i++) {
			char c = value.charAt(i);
			if (!Character.isLetterOrDigit(c) && c != '_' && c != '.' && c != '@')
				return true;
		}
		return false;
	}
}
